import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        //获取blogId，若为空则是博客列表页，若不为空则是博客详情页
        String blogId = req.getParameter("blogId");
        if(blogId == null) {
            //博客列表页
            blogListUser(req, resp);
        } else {
            //博客详情页
            blogDescUser(req, resp, Integer.valueOf(blogId));
        }

    }
    //博客详情页
    private void blogDescUser(HttpServletRequest req, HttpServletResponse resp, int blogId) throws IOException {
        //1.从数据库中获取
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(blogId);
        if(blog == null) {
            resp.setStatus(404);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("该作者不存在");
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.selectById(blog.getUserId());
        if(user == null) {//user是瞎写的
            resp.setStatus(404);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("该作者不存在");
            return;
        }
        user.setPassword("");
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
    //博客列表页
    private void blogListUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.通过会话获取
        HttpSession session = req.getSession();
        if(session == null) {
            resp.sendRedirect("login.html");
            return;
        }
        //2.检验user是否存在
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.sendRedirect("login.html");
            return;
        }
        user.setPassword("");//防止密码泄漏
        //3.返回响应user
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}
